package com.AIDS.AIDSweeper.server.model.DAO;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

public class GoogleJDODAO<T,ID> implements GenericDAO<T, ID> {

	private Class<T> PersistentClass;
	
	@SuppressWarnings("unchecked")
	public GoogleJDODAO() {
		this.PersistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<T> findAll(PersistenceManager pm) {
		List<T> entity;
		Query query = pm.newQuery(PersistentClass);
		try {
			entity = (List<T>)query.execute();
		} finally {
			query.closeAll();
		}
		return entity;
	}

	@Override
	public T findById(ID id,PersistenceManager pm) {
		
		T entity;
		entity = pm.getObjectById(PersistentClass, id);
		return entity;
	}

	@Override
	public T save(T entity, PersistenceManager pm) {
		T result = pm.makePersistent(entity);
		return result;
		
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public boolean exist(ID id, PersistenceManager pm) {
		T entity;
		Query query = pm.newQuery(PersistentClass);
		query.setFilter("id == idParam");
		try {
			entity = (T)query.execute(id);
		} finally {
			query.closeAll();
		}
		return (entity == null);
	}
	
	
}
